package com.easylinkin.linkappapi.grid.models.handler;

import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import com.easylinkin.linkappapi.grid.models.dto.GridSecurityLogExportDTO;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;

import java.util.List;
import java.util.Map;
import java.util.LinkedHashMap;

/**
 * 网格安全员日志Excel多sheet页处理器
 *
 * @author xy
 * @since 2025-01-02
 */
public class GridSecurityLogMultiSheetHandler implements SheetWriteHandler {

    private final String gridName;
    private final Map<String, DaySheetData> dayDataMap;
    
    public static class DaySheetData {
        private String checkTime;
        private String checker;
        private List<GridSecurityLogExportDTO> data;
        private int dayOfMonth;
        
        public DaySheetData(String checkTime, String checker, List<GridSecurityLogExportDTO> data, int dayOfMonth) {
            this.checkTime = checkTime;
            this.checker = checker;
            this.data = data;
            this.dayOfMonth = dayOfMonth;
        }
        
        // getters
        public String getCheckTime() { return checkTime; }
        public String getChecker() { return checker; }
        public List<GridSecurityLogExportDTO> getData() { return data; }
        public int getDayOfMonth() { return dayOfMonth; }
    }

    public GridSecurityLogMultiSheetHandler(String gridName, Map<String, DaySheetData> dayDataMap) {
        this.gridName = gridName;
        this.dayDataMap = dayDataMap;
    }

    @Override
    public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
        // 不需要实现
    }

    @Override
    public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
        Sheet sheet = writeSheetHolder.getSheet();
        Workbook workbook = writeWorkbookHolder.getWorkbook();
        String sheetName = sheet.getSheetName();
        
        // 根据sheet名称获取对应的数据
        DaySheetData dayData = dayDataMap.get(sheetName);
        if (dayData == null) {
            return;
        }
        
        List<GridSecurityLogExportDTO> data = dayData.getData();
        String checkTime = dayData.getCheckTime();
        String checker = dayData.getChecker();
        
        // 创建样式
        createAndApplyStyles(workbook, sheet, data, checkTime, checker);
    }
    
    private void createAndApplyStyles(Workbook workbook, Sheet sheet, List<GridSecurityLogExportDTO> data, 
                                    String checkTime, String checker) {
        // 创建标题样式
        CellStyle titleStyle = workbook.createCellStyle();
        titleStyle.setAlignment(HorizontalAlignment.CENTER);
        titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        Font titleFont = workbook.createFont();
        titleFont.setBold(true);
        titleFont.setFontHeightInPoints((short) 16);
        titleStyle.setFont(titleFont);

        // 创建信息行样式
        CellStyle infoStyle = workbook.createCellStyle();
        infoStyle.setAlignment(HorizontalAlignment.LEFT);
        infoStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        Font infoFont = workbook.createFont();
        infoFont.setFontHeightInPoints((short) 12);
        infoStyle.setFont(infoFont);

        // 创建表头样式
        CellStyle headerStyle = workbook.createCellStyle();
        headerStyle.setAlignment(HorizontalAlignment.CENTER);
        headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        headerStyle.setBorderTop(BorderStyle.THIN);
        headerStyle.setBorderBottom(BorderStyle.THIN);
        headerStyle.setBorderLeft(BorderStyle.THIN);
        headerStyle.setBorderRight(BorderStyle.THIN);
        headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        Font headerFont = workbook.createFont();
        headerFont.setBold(true);
        headerFont.setFontHeightInPoints((short) 12);
        headerStyle.setFont(headerFont);

        // 创建数据样式
        CellStyle dataStyle = workbook.createCellStyle();
        dataStyle.setAlignment(HorizontalAlignment.CENTER);
        dataStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        dataStyle.setBorderTop(BorderStyle.THIN);
        dataStyle.setBorderBottom(BorderStyle.THIN);
        dataStyle.setBorderLeft(BorderStyle.THIN);
        dataStyle.setBorderRight(BorderStyle.THIN);
        dataStyle.setWrapText(true);
        Font dataFont = workbook.createFont();
        dataFont.setFontHeightInPoints((short) 11);
        dataStyle.setFont(dataFont);

        // 插入标题行
        Row titleRow = sheet.createRow(0);
        titleRow.setHeight((short) 600);
        Cell titleCell = titleRow.createCell(0);
        titleCell.setCellValue("网格安全员日志");
        titleCell.setCellStyle(titleStyle);
        // 合并标题行
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 6));

        // 插入信息行
        Row infoRow = sheet.createRow(1);
        infoRow.setHeight((short) 400);
        
        // 作业网格：占三个单元格（A、B、C）
        Cell gridCell = infoRow.createCell(0);
        gridCell.setCellValue(String.format("作业网格：%s", gridName != null ? gridName : ""));
        gridCell.setCellStyle(infoStyle);
        sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 2));
        
        // 填表时间：占两个单元格（D、E）
        Cell timeCell = infoRow.createCell(3);
        timeCell.setCellValue(String.format("填表时间：%s", checkTime != null ? checkTime : ""));
        timeCell.setCellStyle(infoStyle);
        sheet.addMergedRegion(new CellRangeAddress(1, 1, 3, 4));
        
        // 填表人：占两个单元格（F、G）
        Cell checkerCell = infoRow.createCell(5);
        checkerCell.setCellValue(String.format("填表人：%s", checker != null ? checker : ""));
        checkerCell.setCellStyle(infoStyle);
        sheet.addMergedRegion(new CellRangeAddress(1, 1, 5, 6));

        // 插入表头
        Row headerRow = sheet.createRow(2);
        headerRow.setHeight((short) 500);
        String[] headers = {"序号", "检查项目", "检查内容", "检查情况", "存在问题", "督促整改情况", "备注"};
        for (int i = 0; i < headers.length; i++) {
            Cell headerCell = headerRow.createCell(i);
            headerCell.setCellValue(headers[i]);
            headerCell.setCellStyle(headerStyle);
        }

        // 数据从第4行开始（前3行是标题、信息、表头）
        int startRow = 3;
        
        // 记录检查项目的合并信息
        Map<String, Integer> checkItemStartRow = new LinkedHashMap<>();
        Map<String, Integer> checkItemEndRow = new LinkedHashMap<>();
        Map<String, Integer> checkItemSerial = new LinkedHashMap<>();
        
        // 写入数据并记录合并信息
        for (int i = 0; i < data.size(); i++) {
            GridSecurityLogExportDTO item = data.get(i);
            Row dataRow = sheet.createRow(startRow + i);
            dataRow.setHeight((short) 400);
            
            String checkItem = item.getCheckItem();
            
            // 记录检查项目的开始和结束行
            if (!checkItemStartRow.containsKey(checkItem)) {
                checkItemStartRow.put(checkItem, startRow + i);
                // 为相同检查项目设置相同的序号
                int serialNumber = checkItemStartRow.size();
                checkItemSerial.put(checkItem, serialNumber);
            }
            checkItemEndRow.put(checkItem, startRow + i);
            
            // 填充数据
            createCell(dataRow, 0, checkItemSerial.get(checkItem).toString(), dataStyle);
            createCell(dataRow, 1, checkItem != null ? checkItem : "", dataStyle);
            createCell(dataRow, 2, item.getCheckContent() != null ? item.getCheckContent() : "", dataStyle);
            createCell(dataRow, 3, isEmptyOrNull(item.getCheckStatus()) ? "无" : item.getCheckStatus(), dataStyle);
            createCell(dataRow, 4, isEmptyOrNull(item.getProblems()) ? "无" : item.getProblems(), dataStyle);
            createCell(dataRow, 5, isEmptyOrNull(item.getRectification()) ? "无" : item.getRectification(), dataStyle);
            createCell(dataRow, 6, item.getRemark() != null ? item.getRemark() : "", dataStyle);
        }
        
        // 合并相同检查项目的单元格
        for (String checkItem : checkItemStartRow.keySet()) {
            int startRowIndex = checkItemStartRow.get(checkItem);
            int endRowIndex = checkItemEndRow.get(checkItem);
            
            // 如果有多行相同的检查项目，则合并序号和检查项目列
            if (endRowIndex > startRowIndex) {
                // 合并序号列
                sheet.addMergedRegion(new CellRangeAddress(startRowIndex, endRowIndex, 0, 0));
                // 合并检查项目列
                sheet.addMergedRegion(new CellRangeAddress(startRowIndex, endRowIndex, 1, 1));
            }
        }

        // 设置列宽
        sheet.setColumnWidth(0, 2000);  // 序号
        sheet.setColumnWidth(1, 5000);  // 检查项目
        sheet.setColumnWidth(2, 10000); // 检查内容
        sheet.setColumnWidth(3, 4000);  // 检查情况
        sheet.setColumnWidth(4, 5000);  // 存在问题
        sheet.setColumnWidth(5, 5000);  // 督促整改情况
        sheet.setColumnWidth(6, 4000);  // 备注
    }
    
    private void createCell(Row row, int column, String value, CellStyle style) {
        Cell cell = row.createCell(column);
        cell.setCellValue(value);
        cell.setCellStyle(style);
    }
    
    private boolean isEmptyOrNull(String value) {
        return value == null || value.trim().isEmpty();
    }
} 